'use strict'

import { app, protocol, BrowserWindow, screen, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import path from "path";
import Store from 'electron-store'

const isDevelopment = process.env.NODE_ENV !== 'production'
const store = new Store()

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let win

async function createWindow() {
  const workAreaSize = screen.getPrimaryDisplay().workAreaSize
  const zoomFactor = workAreaSize.height + 60 < 1080 ? (workAreaSize.height + 60) / 1080 : 1
  const width = (815 * zoomFactor + 16).toFixed(0)
  const height = (943 * zoomFactor + 16 + 20).toFixed(0)
  const offsetX = workAreaSize.width - width - 7
  let offsetY = ((workAreaSize.height - height) / 2).toFixed(0)
  offsetY = offsetY < 0 ? 0 : offsetY
  // Create the browser window.
  win = new BrowserWindow({
    width: width * 1, // 400 * 2 + 15 + 8 * 2
    height: height * 1,
    x: offsetX,
    y: offsetY * 1,
    frame: false,
    transparent: true,
    resizable: false,
    webPreferences: {
      
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      webSecurity: false
    }
  })

  // 任务栏不显示图标
  win.setSkipTaskbar(true)

  win.once('ready-to-show', () => {
    win.webContents.setZoomFactor(zoomFactor)
    win.show()
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// 单例模式运行
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到myWindow这个窗口
    if (win) {
      win.focus()
    }
  })

  // 创建Window, 加载应用的其余部分
  // This method will be called when Electron has finished
  // initialization and is ready to create browser windows.
  // Some APIs can only be used after this event occurs.
  app.on('ready', async () => {
    createWindow()

    // 监听渲染进程消息
    ipcMain.on('saveInstruments', (event, param) => {
      store.set('instruments', param)
    })
    ipcMain.on('contextMenu', (event, data) => {
      if (data === 'refresh')
        win.reload()
      if (data === 'quit')
        app.quit()
    })
    ipcMain.on('zoomFactor', (event, data) => {
      const workAreaSize = screen.getPrimaryDisplay().workAreaSize
      const zoomFactor = workAreaSize.height + 60 < 1080 ? (workAreaSize.height + 60) / 1080 : 1
      event.returnValue = zoomFactor
    })
  })
}

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}